package com.jcl.recruit.wechat.service;

import com.jcl.core.web.model.ShareUserToken;
import com.jcl.core.utils.CollectionUtils;
import com.jcl.recruit.basic.login.impl.RecruitLoginImpl;
import com.jcl.recruit.basic.login.model.UserExternalLoginInfo;
import com.jcl.recruit.console.logic.ConsoleUserAccessLogic;
import com.jcl.recruit.console.model.ConsoleUserAccess;
import com.jcl.recruit.core.constants.UserExternalLoginConstant;
import com.jcl.recruit.user.logic.UserLogic;
import com.jcl.recruit.user.model.User;
import com.jcl.recruit.wechat.logic.WechatAccessLogic;
import com.jcl.recruit.wechat.utils.WechatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WechatLoginService extends RecruitLoginImpl {

    private static final Logger logger = LoggerFactory.getLogger(WechatLoginService.class);

    @Autowired
    private WechatAccessLogic wechatAccessLogic;

    @Autowired
    private ConsoleUserAccessLogic consoleUserAccessLogic;

    @Autowired
    private UserLogic userLogic;

    public UserExternalLoginInfo accessLogin(WechatUtils.WechatUserInfo userInfo, String state) {

        // 登录
        UserExternalLoginInfo userExternalLoginInfo = new UserExternalLoginInfo();
        List<ConsoleUserAccess> accessList = consoleUserAccessLogic.findListByExternalKey(userInfo.getOpenid(),
                UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                UserExternalLoginConstant.USER_ACCESS_STATUS_USED);
        ConsoleUserAccess userAccess = null;
        if (CollectionUtils.isNotEmpty(accessList)) {
            userAccess = accessList.get(0);
        }
        // 用户不存在， 创建用户到 默认企业
        if (null == userAccess) {
            userAccess = wechatAccessLogic.registerDefault(userInfo.getCorpCode(), userInfo.getOpenid(),
                    userInfo.getUnionid(), userInfo.getNickname(), userInfo.getHeadimgurl());
        }
        userExternalLoginInfo = new UserExternalLoginInfo();
        userExternalLoginInfo.setUsername(userAccess.getUsername());
        userExternalLoginInfo.setPassword(userAccess.getPassword());
        userExternalLoginInfo.setUserId(userAccess.getUserId());
        userExternalLoginInfo.setCorpCode(userAccess.getCorpCode());
        return userExternalLoginInfo;
    }

    /* *
     * @Author yyliu
     * @Description 微信邀约登录
     * @Date 9:38 2018/9/14
     * @Param [code]
     * @return com.example.core.wechat.WechatUtils.AccessLoginInfo
     **/
    public WechatUtils.AccessLoginInfo accessLoginByInvite(WechatUtils.WechatUserInfo userInfo,
                                                           String accessKey) {

        WechatUtils.AccessLoginInfo loginInfo = new WechatUtils.AccessLoginInfo();
        // 获取登录的微信用户信息
        ShareUserToken tokenInfo = ShareUserToken.decodeInviteToken(accessKey);
        if (null == tokenInfo) {
            loginInfo.setCode("error");
            loginInfo.setMsg("state param is error !");
            return loginInfo;
        }

        // 1、判断是否 邀约人自己点击，如果是则直接登录
        ConsoleUserAccess inviter = consoleUserAccessLogic.findWechatOneByUserId(
                Integer.valueOf(tokenInfo.getUserId()));
        if (null != inviter) {
            if (inviter.getExternalKey().equals(loginInfo.getOpenId())) {
                consoleUserAccessLogic.changeUseStatusToUnused(
                        inviter.getExternalKey(), UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT);
                inviter.setStatus(UserExternalLoginConstant.USER_ACCESS_STATUS_USED);
                consoleUserAccessLogic.updateAccess(inviter);
                User user = userLogic.findOne(inviter.getCorpCode(), inviter.getUserId());
                loginInfo.setUser(user);
                loginInfo.setCode("login");
                loginInfo.setUserExternalAccess(inviter);

                return loginInfo;
            }
        }

        // 2、判断用户是否已经注册当前邀约企业， 如果是则直接登录，否则注册
        ConsoleUserAccess userAccess = consoleUserAccessLogic.
                findOneByExternalKeyAndCode(userInfo.getOpenid(), tokenInfo.getCorpCode());
        if (null != userAccess && null != userAccess.getUserId()) {
            // 当前用户存在，直接登录
            consoleUserAccessLogic.changeUseStatusToUnused(
                    userInfo.getOpenid(), UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT);
            // 默认使用当前企业
            userAccess.setStatus(UserExternalLoginConstant.USER_ACCESS_STATUS_USED);
            consoleUserAccessLogic.updateAccess(userAccess);

            User user = userLogic.findOneById(userAccess.getUserId());
            loginInfo.setUser(user);
            loginInfo.setCode("login");
            loginInfo.setUserExternalAccess(userAccess);
            return loginInfo;
        } else {
            // 当前用户需要注册
            List<ConsoleUserAccess> userAccessList = consoleUserAccessLogic.findListByExternalKey(
                    userInfo.getOpenid(), UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                    UserExternalLoginConstant.USER_ACCESS_STATUS_TEMP);

            if (CollectionUtils.isEmpty(userAccessList)) {
                // 用户不存在， 默认使用 临时账户
                userAccess = wechatAccessLogic.addTempUserAccess(userInfo.getOpenid(), userInfo.getUnionid(),
                        userInfo.getNickname(),
                        UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                        UserExternalLoginConstant.USER_ACCESS_STATUS_TEMP);
            } else {
                userAccess = userAccessList.get(0);
            }

            loginInfo.setCode("register");
            loginInfo.setUserExternalAccess(userAccess);
            return loginInfo;
        }
    }


    public WechatUtils.WechatUserInfo getWechatUserInfo(String code) {
        // 获取微信登录的token和openId
        WechatUtils.WechatCodeMessage codeMessage = WechatUtils.getCodeObject(code);

        // 获取登录的微信用户信息
        WechatUtils.WechatUserInfo userInfo = WechatUtils.getUserInfoObject(codeMessage.getAccess_token(),
                codeMessage.getOpenid());

        return userInfo;
    }

}
